package com.zzyl.nursing.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zzyl.nursing.service.WechatService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;

@Service
public class WechatServiceImpl implements WechatService {
    //登录
    private static final String GET_OPENID_URL = "https://api.weixin.qq.com/sns/jscode2session?grant_type=authorization_code";
    //获取token
    private static final String GET_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";
    //获取手机号
    private static final String GET_PHONE_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";

    @Value("${wechat.appid}")
    private String appid;
    @Value("${wechat.secret}")
    private String secret;
    /**
     * 获取openId
     * @param code
     * @return
     */
    @Override
    public String getOpenId(String code) {
        HashMap<String, Object> params = new HashMap<>();
        params.put("appid", appid);
        params.put("secret", secret);
        params.put("js_code", code);
        String result = HttpUtil.get(GET_OPENID_URL, params);
        //将结果解析成json对象
        JSONObject entries = JSONUtil.parseObj(result);
        if (ObjectUtil.isNotEmpty(entries.getInt("errcode"))){
            throw new RuntimeException(entries.getStr("errmsg"));
        }

        return entries.getStr("openid");
    }

    /**
     * 获取手机号
     * @param phoneCode
     * @return
     */
    @Override
    public String getPhone(String phoneCode) {
        String token = this.getToken();
        String url = GET_PHONE_URL + token;
        HashMap<Object, Object> params = new HashMap<>();
        params.put("code", phoneCode);
        String jsonStr = JSONUtil.toJsonStr(params);
        String result = HttpUtil.post(url, jsonStr);
        JSONObject entries = JSONUtil.parseObj(result);
        if (entries.getInt("errcode")!=0){
            throw new RuntimeException(entries.getStr("errmsg"));
        }
        JSONObject phoneInfo = entries.getJSONObject("phone_info");
        String phoneNumber = phoneInfo.getStr("phoneNumber");

        return phoneNumber;
    }

    private String getToken() {
        HashMap<String, Object> params = new HashMap<>();
        params.put("appid", appid);
        params.put("secret", secret);
        String result = HttpUtil.get(GET_TOKEN_URL, params);
        JSONObject entries = JSONUtil.parseObj(result);
        if (ObjectUtil.isNotEmpty(entries.getInt("errcode"))){
            throw new RuntimeException(entries.getStr("errmsg"));
        }
        String accessToken = entries.getStr("access_token");
        return accessToken;
    }
}
